/**  条状进度条  **/
/**  v-loading2="boolean"  **/
/**  v-loading2="{
      show: boolean
      text: string
    }"  **/

import type { ObjectDirective } from 'vue'

type BindingValueType =
  | {
      show: boolean
      text: string
    }
  | boolean

const initLoading = (el, binding) => {
  const value: BindingValueType = binding.value
  let show,
    text = '正在加载中...'
  if (typeof value === 'boolean') {
    show = value
  } else {
    show = value.show
    text = value.text
  }
  switch (show) {
    case true:
      setLoading(el, text)
      break
    case false:
      removeLoading(el)
      break
  }
}

export const loading: ObjectDirective = {
  mounted(el, binding) {
    initLoading(el, binding)
  },
  updated(el, binding) {
    initLoading(el, binding)
  },
  unmounted(el) {
    removeLoading(el)
  }
}

function setLoading(el: HTMLElement, text: string) {
  removeLoading(el)
  const parentEl = el
  const loadingBoxEl = document.createElement('div')
  const loader = document.createElement('div')
  const elPosition = parentEl.getAttribute('position')
  if (elPosition == null || elPosition == 'static') {
    parentEl.style.position = 'relative'
  } else {
    parentEl.style.position = elPosition
  }
  loadingBoxEl.className = 'loading-box'
  loader.className = 'loader'
  loader.innerHTML = `<div class="loader-item" data-content="${text}"></div>`
  loadingBoxEl.appendChild(loader)
  parentEl.appendChild(loadingBoxEl)
}

function removeLoading(el: HTMLElement) {
  const loader = el.querySelector('.loading-box')
  loader?.remove()
}
